import pandas
import requests
import json
import multiprocessing as mp
import datetime
import re
import time
import newAlgor
import os

HEADERS = {
    "Origin": "https://xueqiu.com",
    "Referer": "https://xueqiu.com/S/SZ002372",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36",
    "Connection": "close",
    "cookie": "device_id=24700f9f1986800ab4fcc880530dd0ed; s=dp11eckvkd; cookiesu=221583286466240; Hm_lvt_1db88642e346389874251b5a1eded6e3=1582849941,1583115672,1583195966,1583286466; xq_a_token=66e8a3f551509aa69374d910934c68b74e4a3531; xqat=66e8a3f551509aa69374d910934c68b74e4a3531; xq_r_token=05bb35ff0d538ea379799710359c5135ed3d1ba9; xq_id_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJ1aWQiOjE4OTI5OTIwODcsImlzcyI6InVjIiwiZXhwIjoxNTg1ODc4NDg0LCJjdG0iOjE1ODMyODY0ODQ1MDIsImNpZCI6ImQ5ZDBuNEFadXAifQ.pEpvGMXK2dSM-bHADNOU_x9txymZFpEgv0xLZw9wu-fcmNicE16n-qKWfGS9SAtXw9XGVX5tbSHq6n7XqBeOZL86HON3_T44d1WcDCvzF6lWldMWs0aenhxA98z4bqpiWI_UcS4lIHbFYo3TBp-L4J6_zj7FSu3Px2KW2MRxOdOpHfqs2PGldMEfQELK_TZMSYdLjS9CC4VF84EpIPl1HQaBLcfXg98rAV7eSGKzm7gg9QgEYRyRcGh4W_P_crSDaGl37RNMzZOPooDZyWNqMjrLRFdncid9yQNX1VW7zcIIpa5igK9NcZQXwdwZBjSAg--19ZEPbq9X6DrETc1PvA; xq_is_login=1; u=1892992087; Hm_lpvt_1db88642e346389874251b5a1eded6e3=1583286486"
}
format_time = datetime.datetime.now().strftime('%Y-%m-%d') + " 00:00:00"
ts = time.strptime(format_time, "%Y-%m-%d %H:%M:%S")
TIMESTAMP = int(time.mktime(ts)*1000)

def createMask():
    codeArr = []
    with open('Stocks.csv', "r", encoding='utf-8') as fd:
        lines = fd.readlines()
        for line in lines:
            line = line.strip().split(",")
            codeArr.append({
                "code": line[2],
                "name": line[3]
            })
    pool = mp.Pool(processes=4)
    res = pool.map(excuteMask, codeArr)
    pool.close()
    pool.join()
    makeResult(res)
def excuteMask(data):
    code = data["code"]
    type = 'SH' if re.match('6[0-9]{5}', code) else 'SZ'
    URL = 'https://stock.xueqiu.com/v5/stock/chart/kline.json?symbol=%s%s&begin=%s&period=day&type=before&count=-5'%(type,code,TIMESTAMP)
    try:
        json_data = requests.get(url=URL, headers=HEADERS, allow_redirects=False).text
        _json = json.loads(json_data)
        print(_json)
        algor = newAlgor.Algorithm(_json['data'])
        type = ""
        if algor.sharesSize1():
            type = 1
        if algor.sharesSize2():
            type = 2
        # if algor.sharesSize3():
        #     type = 3
        if algor.sharesSize4():
            type = 4
        return "" if type == "" else {
            "code": code,
            "name": data["name"],
            "type": type
        }
    except:
        time.sleep(5)
    return ""

def makeResult(res):
    print(res)
    # 删除result.txt
    if os.path.exists('result.txt'):
        os.remove('result.txt')
    for item in res:
        if not item == "":
            fp = open('result.txt', 'a', encoding='utf-8')
            fp.write('%s,%s,%s\n' % (item["code"], item["name"], item["type"]))
            fp.close()
if __name__ == '__main__':
    createMask()